<!--
Tests that anchors can be created off of AR hit test results when plane is present.
-->
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="../resources/webxr_e2e.css">
  </head>
  <body>
    <canvas id="webgl-canvas"></canvas>
    <script src="../../../../../../third_party/blink/web_tests/resources/testharness.js"></script>
    <script src="../resources/webxr_e2e.js"></script>
    <script>var shouldAutoCreateNonImmersiveSession = false;</script>
    <script src="../resources/webxr_boilerplate.js"></script>
    <script>
      setup({single_test: true});

      const TestState = Object.freeze({
        "Initial":  0,
        "HitTestSourceAvailable": 1,  // hitTestSource variable is guaranteed to be non-null in this state
        "AnchorRequested": 2,
        });

      let testState = TestState.Initial;
      let hitTestSource = null;

      function stepStartHitTesting() {
        const sessionInfo = sessionInfos[sessionTypes.AR];
        sessionInfo.currentSession.requestHitTestSource({
          space: sessionInfo.currentRefSpace,
          offsetRay: new XRRay()
        }).then((hts) => {
          // Mark that the hit test source is available.
          hitTestSource = hts;
          testState = TestState.HitTestSourceAvailable;
        }).catch((err) => {
          assert_unreached("XRSession.requestHitTestSource() promise rejected.");
        });

        onARFrameCallback = (session, frame) => {
          switch(testState) {
            case TestState.Initial: {
              // In initial state, there is nothing to do (we're waiting for hit test source).
              return;
            }
            case TestState.HitTestSourceAvailable: {
              // Since we already have a hit test source, let's get its results and create an anchor.
              const results = frame.getHitTestResults(hitTestSource);
              if(results.length) {
                const result = results[0];
                result.createAnchor().then((anchor) => {
                  // Mark the test as done, there is no need to pump rAFcb at this point anymore.
                  done();
                }).catch((err) => {
                  // Fail the test.
                  assert_unreached("XRHitTestResult.createAnchor() promise rejected.");
                });

                // Mark that we are waiting for anchor creation.
                testState = TestState.AnchorRequested;
              }
              return;
            }
            default:
              return;
          }
        };
      }
    </script>
  </body>
</html>
